using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System;
using System.Diagnostics;
using System.Threading.Tasks;

namespace CKY.AgentPlatform.Performance
{
    /// <summary>
    /// 性能监控中间件
    /// 用于监控每个HTTP请求的响应时间和性能指标
    /// </summary>
    public class PerformanceMonitoringMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<PerformanceMonitoringMiddleware> _logger;
        private readonly PerformanceMetrics _metrics;

        public PerformanceMonitoringMiddleware(
            RequestDelegate next,
            ILogger<PerformanceMonitoringMiddleware> logger,
            PerformanceMetrics metrics)
        {
            _next = next;
            _logger = logger;
            _metrics = metrics;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            var stopwatch = Stopwatch.StartNew();
            var path = context.Request.Path;
            var method = context.Request.Method;

            try
            {
                // 记录请求开始
                _logger.LogDebug("开始处理请求: {Method} {Path}", method, path);

                // 执行下一个中间件
                await _next(context);

                // 记录成功请求
                stopwatch.Stop();
                _metrics.RecordRequest(path, method, context.Response.StatusCode, stopwatch.ElapsedMilliseconds);

                _logger.LogDebug("请求处理完成: {Method} {Path} - {StatusCode} - {ElapsedMs}ms",
                    method, path, context.Response.StatusCode, stopwatch.ElapsedMilliseconds);
            }
            catch (Exception ex)
            {
                // 记录异常请求
                stopwatch.Stop();
                _metrics.RecordRequest(path, method, 500, stopwatch.ElapsedMilliseconds);
                _metrics.RecordError(path, ex.GetType().Name);

                _logger.LogError(ex, "请求处理异常: {Method} {Path} - {ElapsedMs}ms",
                    method, path, stopwatch.ElapsedMilliseconds);

                throw;
            }
        }
    }
}